﻿/*
 * Twipler - Twitter Web Client with features.
 *  
 *  Copyright (C) 2009, 2010. Ian Quigley
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details. 
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>. 
 */

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Twipler.App;
using Twipler.WebApp;


using Twipler.Data.Access;
using Twipler.Data.Entity.Theme;
using Twipler.Xtensions;
using Twipler.App.Parse.Html;
using Twipler.App.Parse;

namespace Settings.Theme
{
    [RequireUser()]
    [QueryStringHash]
    public partial class ContainerList : Page
    {
        private bool pageReadonly;

        protected void Page_Load(object sender, EventArgs e)
        {
            pageReadonly = Request.QueryStringBool("ro", false);
            editContainer.Readonly = pageReadonly;

            if (!IsPostBack)
            {
                UpdateDisplay();
                txtBox.Attributes.Add("onkeydown", "return catchTab(this,event);");

                Current.PageProducer = null;

                grdContainer.ShowFooter = !pageReadonly;
                grdBlock.ShowFooter = !pageReadonly;
            }
        }

        
        protected void grdContainer_ItemCommand(object source, DataGridCommandEventArgs e)
        {
            int containerId = 0;

            if (e.Item.ItemType != ListItemType.Footer)
            {
                Literal litId = (Literal)e.Item.FindControl("litId");
                containerId = int.Parse(litId.Text);
            }

            editContainer.Visible = true;
            editBlock.Visible = false;

            Container container;

            switch (e.CommandName)
            {
                case "New":
                    container= new Container();
                    container.ParentDesign = Factory.Design.GetById(Request.QueryStringInt("designId").Value, false);
                    
                    editContainer.Entity = container;
                    editContainer.Visible = true;
                    editContainer.UpdateDisplay();
                    mpeEditEntity.Show();
                    break;
                    
                case "Edit":
                    editContainer.Entity = Factory.Container.GetById(containerId, false);
                    editContainer.Visible = true;
                    editContainer.UpdateDisplay();
                    mpeEditEntity.Show();
                    break;

                case "View":
                    editContainer.Entity = Factory.Container.GetById(containerId, false);
                    editContainer.Visible = true;
                    editContainer.Readonly = true;
                    editContainer.UpdateDisplay();
                    mpeEditEntity.Show();
                    break;
                
                case "Html":
                    container = Factory.Container.GetById(containerId, false);
                    if (container == null)
                        return;

                    Current.EntityEdit = container;
                    lblTitle.Text = string.Format("Editting: {0}.html", container.Title);
                    txtBox.Text = container.Source;
                    litErrors.Text = "";
                    mpeTextEdit.Show();
                    break;

                case "Delete":
                    Factory.Container.Delete(Factory.Container.GetById(containerId, false));
                    UpdateDisplay();
                    break;
            }

        }

        protected void grdBlock_ItemCommand(object source, DataGridCommandEventArgs e)
        {
            int blockId = 0;

            if (e.Item.ItemType != ListItemType.Footer)
            {
                Literal litId = (Literal)e.Item.FindControl("litId");
                blockId = int.Parse(litId.Text);
            }
            
            editContainer.Visible = false;
            editBlock.Visible = true;

            Block block;
            
            switch (e.CommandName)
            {
                case "New":
                    block = new Block();
                    block.ParentDesign = Factory.Design.GetById(Request.QueryStringInt("designId").Value, false);
                    
                    editBlock.Visible = true;
                    editBlock.Entity = block;
                    editBlock.UpdateDisplay();
                    mpeEditEntity.Show();
                    break;

                case "Edit":
                    editBlock.Visible = true;
                    editBlock.Entity = Factory.Block.GetById(blockId, false);
                    editBlock.UpdateDisplay();
                    mpeEditEntity.Show();
                    break;

                case "Html":
                    block = Factory.Block.GetById(blockId, false);
                    if (block == null)
                        return;

                    Current.EntityEdit = block;
                    
                    lblTitle.Text = string.Format("Editting: {0}", block.Code);
                    txtBox.Text = block.Content;
                    litErrors.Text = "";
                    mpeTextEdit.Show();
                    break;


                case "Delete":
                    Factory.Block.Delete(Factory.Block.GetById(blockId, false));
                    UpdateDisplay();
                    break;
            }
        }

        protected void editContainer_Update()
        {
            UpdateDisplay();
        }

        private void UpdateDisplay()
        {
            int designId = Request.QueryStringInt("designId").GetValueOrDefault();
            if (designId > 0)
            {
                Design design = Factory.Design.GetById(designId, false);
                if (design == null)
                    return;

                litBreadcrumb.Text = "Pages for : " + design.Name;
                
                grdContainer.DataSource = design.Containers();
                grdContainer.DataBind();

                grdBlock.DataSource = design.Blocks();
                grdBlock.DataBind();
            }

            if (pageReadonly)
                editContainer.Visible = false;
        }

        protected void grdContainer_ItemDataBound(object sender, DataGridItemEventArgs e)
        {
            if (pageReadonly == true)
                return;

            if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem)
                return;

            Button btnDelete = (Button)e.Item.FindControl("btnDelete");
            btnDelete.Visible = ((Container)e.Item.DataItem).UserCanModify();
            btnDelete.Attributes.Add("onclick", "return window.confirm('Confirm deletion of container');");
            
            Button btnEdit = (Button)e.Item.FindControl("btnEdit");
            if (((Container)e.Item.DataItem).UserCanModify() == false)
            {
                btnEdit.Text = "View";
                btnEdit.CommandName = "View";
            }
            else
            {
                btnEdit.Text = "Edit";
                btnEdit.CommandName = "Edit";
            }
            
        }

        protected void grdBlock_ItemDataBound(object sender, DataGridItemEventArgs e)
        {
            if (pageReadonly == true)
                return;

            if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem)
                return;

            Button btnDelete = (Button)e.Item.FindControl("btnDelete");
            btnDelete.Visible = ((Block)e.Item.DataItem).UserCanModify();
            btnDelete.Attributes.Add("onclick", "return window.confirm('Confirm deletion of block');");
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (Current.EntityEdit.GetType() == typeof(Container))
            {
                Container container = (Container)Current.EntityEdit;
                container.Source = txtBox.Text;

                Template temp = new Template(container.Source);
                temp.Parse();

                if (temp.HasErrors)
                {
                    litErrors.Text = "<div style=\"background:#ffe; border: 1px solid #cc9;\">";
                    
                    foreach (ParseError error in temp.Errors)
                    {
                        litErrors.Text += string.Format("At <a href=\"javascript:setFocus('{0}',{1});\">{1}</a> {2}</br>", txtBox.ClientID, error.Position, error.Message);
                        mpeTextEdit.Show();
                    }
                    litErrors.Text += "</div>";
                }
                else
                {

                    Factory.Container.SaveOrUpdate(container);
                }
            }

            if (Current.EntityEdit.GetType() == typeof(Block))
            {
                Block block = (Block)Current.EntityEdit;
                block.Content = txtBox.Text;
                Factory.Block.SaveOrUpdate(block);
            }
        }
    }
}